﻿using System;
using System.Collections.Generic;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using Cms.Application.Admin.Presenters;
using Cms.Application.Admin.Views;
using Cms.Domain;
using Cms.Utilities;
using Cms.Web.Framework.Controls;
using Cms.Web.UI.Admin.HelperClasses;
using iLib.Web.UI;
using Content = Cms.Domain.Content;
using MasterTemplate = Cms.Domain.MasterTemplate;
using SortDirection = Cms.Domain.SortDirection;

namespace Cms.Web.UI.Admin
{
    public partial class SearchContent : AdminPage, ISearchContentView
    {
        private SearchContentPresenter _presenter;

        #region ISearchContentView Members

        public void SetLocales(IList<Locale> locales)
        {
            ddlLocales.Items.Clear();
            foreach (Locale l in locales)
                ddlLocales.Items.Add(new ListItem(l.GetTranslation(Localization).Name, l.ID.ToString()));
        }

        public void SetContentList(IList<Content> content, int itemCount, int currentPage, int pageSize)
        {
            pnlUpper.Visible = true;
            upperPages.PageSize = pageSize;
            upperPages.CurrentPage = currentPage;
            upperPages.ItemCount = itemCount;
            pnlLower.Visible = pnlUpper.Visible;
            lowerPages.PageSize = upperPages.PageSize;
            lowerPages.CurrentPage = upperPages.CurrentPage;
            lowerPages.ItemCount = upperPages.ItemCount;
            pnlPreviews.Visible = false;
            pnlList.Visible = false;
            if (ShowPreviews)
            {
                pnlPreviews.Visible = true;
                rpContentWithPreviews.DataSource = content;
                rpContentWithPreviews.DataBind();
            }
            else
            {
                pnlList.Visible = true;
                rpContentList.DataSource = content;
                rpContentList.DataBind();
            }
            // Handle no hits
            trNoHits1.Visible = content.Count == 0;
            trNoHits2.Visible = trNoHits1.Visible;
            if (!Page.IsPostBack && content.Count == 0)
            {
                // This is only necessary upon PageLoad, otherwise this is taken care of in the AJAX EndRequest handler.
                ClientScriptProxy.Current.RegisterStartupScript(pnlActions, GetType(), "hidePaneOverlay", "cms.Lists.HidePaneOverlays();", true);
            }
        }

        public int SelectedLocaleID
        {
            get { return int.Parse(ddlLocales.SelectedValue); }
            set { ddlLocales.SelectedValue = value.ToString(); }
        }

        public string ContextTranslationFile
        {
            get { return "Admin/Translations/SearchContent.xml"; }
        }

        public void SetCategories(IList<Category> rootCategories)
        {
            ddlCategories.Items.Clear();
            ddlCategories.Items.Add(new ListItem(GetText(this, "AllCategories"), "-1"));
            CategoriesDropDownHelper.SetCategoryTree(ref ddlCategories, 0, rootCategories);
        }

        public int SelectedCategoryID
        {
            get { return int.Parse(ddlCategories.SelectedValue); }
            set { ddlCategories.SelectedValue = value.ToString(); }
        }

        public string ContentName
        {
            get { return txtContentName.Text; }
            set { txtContentName.Text = value; }
        }
        
        public string FilterState
        {
            get { return ViewState["FilterState"] == null ? "" : ViewState["FilterState"].ToString(); }
            set { ViewState["FilterState"] = value; }
        }
        
        public int SelectedPageSize
        {
            get { return int.Parse(ddlPageSizes.SelectedValue); }
            set { ddlPageSizes.SelectedValue = value.ToString(); }
        }

        public void SetMasterTemplates(IList<MasterTemplate> masterTemplates)
        {
            ddlMasterTemplates.Items.Clear();
            foreach (MasterTemplate mt in masterTemplates)
                ddlMasterTemplates.Items.Add(new ListItem(mt.Name, mt.ID.ToString()));
        }

        public int SelectedMasterTemplateID
        {
            get { return int.Parse(ddlMasterTemplates.SelectedValue); }
            set { ddlMasterTemplates.SelectedValue = value.ToString(); }
        }
        
        public bool ShowPreviews
        {
            get { return chkShowPreviews.Checked; }
            set { chkShowPreviews.Checked = value; }
        }

        public ContentSortMode SortMode
        {
            get { return (ContentSortMode)Enum.Parse(typeof(ContentSortMode), ddlSortModes.SelectedValue, true); }
            set { ddlSortModes.SelectedValue = value.ToString(); }
        }

        public SortDirection SortDirection
        {
            get { return (SortDirection)Enum.Parse(typeof(SortDirection), ddlSortDirections.SelectedValue, true); }
            set { ddlSortDirections.SelectedValue = value.ToString(); }
        }

        #endregion

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            _presenter = new SearchContentPresenter(this);
            HeadingText = GetText(this, "Heading");
            if (!Page.IsPostBack)
            {
                ddlSortModes.Items.Add(new ListItem(GetText(this, "llSortKey"), "SortKey"));
                ddlSortModes.Items.Add(new ListItem(GetText(this, "llPublishedTimestamp"), "PublishedTimestamp"));
                ddlSortDirections.Items.Add(new ListItem(GetText(this, "llSortDirectionAscending"), "Ascending"));
                ddlSortDirections.Items.Add(new ListItem(GetText(this, "llSortDirectionDescending"), "Descending"));
                _presenter.Initialize();
                HeadingIcon = litIcon.Text;
            }
            lbDelete.OnClientClick = "return cms.Dialogs.ConfirmLinkButton(this, " +
                                     "function (status) { " +
                                     "if (status == 'ok') " +
                                     "cms.Lists.ShowPaneOverlay('contentPaneOverlay');" +
                                     "else " +
                                     "cms.Lists.HidePaneOverlays(); " +
                                     "}, " +
                                     "'" + GetText(this, "DeleteHeader") + "', " +
                                     "'" + GetText(this, "DeleteMessage") + "', " +
                                     "'" + GetText(this, "DeleteOK") + "', " +
                                     "'" + GetText(this, "DeleteCancel") + "', " +
                                     "true, " +
                                     "cms.Lists.CurrentName);";
        }


        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);
            hlNew.NavigateUrl = "Admin/EditContent.aspx?ContentID=-2" +
                                "&LocaleID=" + SelectedLocaleID +
                                "&MasterTemplateID=" + SelectedMasterTemplateID +
                                "&SaveReturnUrl=" + Server.UrlEncode("EditContentPreview.aspx?id=-2") +
                                "&CancelReturnUrl=" + Server.UrlEncode("SearchContent.aspx") +
                                "&SelectedCategory=" + SelectedCategoryID;
            if (!string.IsNullOrEmpty(Request.QueryString["browseitemdata"]))
            {
                hlCancel.Visible = true;
                hlCancel.NavigateUrl = "Admin/" + Server.UrlDecode(Misc.GetBrowseItemDataValue(Request.QueryString["browseitemdata"], "referrer"));
            }
            else
            {
                hlCancel.Visible = false;
                lbSelect.Visible = false;
            }
            upnlButtons.Update();
        }


        protected void lbSelect_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(Request.QueryString["browseitemdata"]))
            {
                return;
            }
            int contentID = int.Parse(hidSelectedContentID.Value.Substring(1));
            string areaID = Misc.GetBrowseItemDataValue(Request.QueryString["browseitemdata"], "AreaID");
            string containerType = Misc.GetBrowseItemDataValue(Request.QueryString["browseitemdata"], "ContainerType");
            int containerID = int.Parse(Misc.GetBrowseItemDataValue(Request.QueryString["browseitemdata"], "ContainerID"));
            _presenter.ShareContent(contentID, areaID, containerType, containerID);
            string url = Url.VirtualPath + "Admin/" + Server.UrlDecode(Misc.GetBrowseItemDataValue(Request.QueryString["browseitemdata"], "referrer"));
            ClientScriptProxy.Current.RegisterStartupScript(pnlButtonActions, GetType(), "selectFile", "window.location.href = '" + url + "';", true);
        }


        protected void rpContentWithPreviews_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType != ListItemType.Item && e.Item.ItemType != ListItemType.AlternatingItem)
                return;
            var content = (Content) e.Item.DataItem;
            var litID = (Literal) e.Item.FindControl("litID");
            var litName = (Literal) e.Item.FindControl("litName");
            var litCategories = (Literal) e.Item.FindControl("litCategories");
            var litSortKey = (Literal) e.Item.FindControl("litSortKey");
            var litCreated = (Literal)e.Item.FindControl("litCreated");
            var litPublishedDate = (Literal)e.Item.FindControl("litPublishedDate");
            var litSystemID = (Literal)e.Item.FindControl("litSystemID");
            var ifrContentPreview = (HtmlGenericControl) e.Item.FindControl("ifrContentPreview");
            litID.Text = "<span id=\"D" + content.ID + "\">";
            litName.Text = content.Name;
            litSystemID.Text = content.ID.ToString();
            SetupCategories(litCategories, content);
            litSortKey.Text = !string.IsNullOrEmpty(content.SortKey) ? content.SortKey : "-";
            ifrContentPreview.Attributes.Add(
                "src", 
                "Admin/ContentPreview.aspx?LocaleID=" + SelectedLocaleID +
                                                    "&MasterTemplateID=" + SelectedMasterTemplateID +
                                                    "&ContentID=" + content.ID);
            SetupCreated(litCreated, content);
            SetupPublishedDate(litPublishedDate, content);

            // Show Created and Created By for published content and also for the latest version (if there is a later version than published)
            // Make it possible to switch the preview between them!

            //ContentTranslation translation = content.GetTranslation(SelectedLocaleID);
            //if (translation.PublishedVersion != null)
            //{
            //    litCreated.Text = GetText(this, "llCreatedHeader2")
            //        .Replace("[DateTime]", translation.PublishedVersion.GetCreatedDateTime().ToShortDateString())
            //        .Replace("[Name]", translation.PublishedVersion.Author.Fullname);
            //}
            //else
            //{
            //    if (translation.Versions.Count > 0)
            //    {
            //        litCreated.Text = GetText(this, "llCreatedHeader2")
            //            .Replace("[DateTime]", translation.Versions.Last().GetCreatedDateTime().ToShortDateString())
            //            .Replace("[Name]", translation.Versions.Last().Author.Fullname);
            //    }
            //}
        }


        protected void rpContentList_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType != ListItemType.Item && e.Item.ItemType != ListItemType.AlternatingItem)
            {
                return;
            }
            var content = (Content) e.Item.DataItem;
            var litID = (Literal) e.Item.FindControl("litID");
            var litName = (Literal) e.Item.FindControl("litName");
            var litCategories = (Literal) e.Item.FindControl("litCategories");
            var litCreated = (Literal)e.Item.FindControl("litCreated");
            var litPublishedDate = (Literal)e.Item.FindControl("litPublishedDate");
            var litSortKey = (Literal)e.Item.FindControl("litSortKey");
            var litSystemID = (Literal) e.Item.FindControl("litSystemID");
            litID.Text = "<span id=\"D" + content.ID + "\">";
            litName.Text = content.Name;
            litSystemID.Text = content.ID.ToString();
            SetupCategories(litCategories, content);
            litSortKey.Text = content.SortKey;
            SetupCreated(litCreated, content);
            SetupPublishedDate(litPublishedDate, content);
        }

        private void SetupCategories(Literal litCategories, Content content)
        {
            foreach (Category category in content.Categories)
            {
                litCategories.Text += category.Name + ", ";
            }
            if (content.Categories.Count > 0)
            {
                litCategories.Text = litCategories.Text.Substring(0, litCategories.Text.Length - 2);
            }
        }

        private void SetupCreated(Literal litCreated, Content content)
        {
            litCreated.Text = GetText(this, "llCreatedHeader2")
                .Replace("[DateTime]", content.Created.ToShortDateString())
                .Replace("[Name]", content.CreatedBy.Fullname);
        }

        private void SetupPublishedDate(Literal litPublishedDate, Content content)
        {
            litPublishedDate.Text = GetText(this, "llPublishedDateHeader") + ": ";
            if (content.StartPublishing.HasValue)
            {
                litPublishedDate.Text += content.StartPublishing.Value.ToShortDateString();
            }
            if (content.StartPublishing.HasValue || content.EndPublishing.HasValue)
            {
                litPublishedDate.Text += "&mdash;";
            }
            if (content.EndPublishing.HasValue)
            {
                litPublishedDate.Text += content.EndPublishing.Value.ToShortDateString();
            }
            if (!content.StartPublishing.HasValue & !content.EndPublishing.HasValue)
            {
                litPublishedDate.Text += GetText(this, "llAlwaysPublished");
            }
        }

        protected void lbDelete_Click(object sender, EventArgs e)
        {
            _presenter.Delete(int.Parse(hidSelectedContentID.Value.Substring(1)));
            upnlContent.Update();
            ClientScriptProxy.Current.RegisterStartupScript(pnlActions, GetType(), "initList", "initList();", true);
        }


        protected void lbSearch_Click(object sender, EventArgs e)
        {
            _presenter.SetContent(0, true);
            upnlContent.Update();
            ClientScriptProxy.Current.RegisterStartupScript(pnlActions, GetType(), "initList", "initList();", true);
        }

        protected void PagedNavigation_Click(int currentPage)
        {
            _presenter.SetContent(currentPage, false);
            upnlContent.Update();
            ClientScriptProxy.Current.RegisterStartupScript(pnlActions, GetType(), "initList", "initList();", true);
        }


        protected void PagedNavigation_Ready(bool visible)
        {
            pnlUpper.Visible = visible;
            pnlLower.Visible = pnlUpper.Visible;
        }
    }
}